<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<script type="text/javascript" src="${pageContext.request.contextPath}/lib/geoxml3.js"></script>
<script type="text/javascript"
        src="http://maps.googleapis.com/maps/api/js?v=3.6&sensor=false&libraries=geometry">
</script>
<%--<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>--%>

<%--<script type="text/javascript"
        src="http://maps.googleapis.com/maps/api/js?v=3.6&sensor=false&libraries=geometry">
</script>--%>

<%--<script type="text/javascript" src="http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js">
</script>--%>
<%--
<script type="text/javascript"
        src="${pageContext.request.contextPath}/lib/maps.google.polygon.containsLatLng.js">
</script>--%>
<script type="text/javascript">
var map;
// Create a meausure object to store our markers, MVCArrays, lines and polygons
var measure = {
    mvcLine: new google.maps.MVCArray(),
    mvcPolygon: new google.maps.MVCArray(),
    mvcMarkers: new google.maps.MVCArray(),
    line: null,
    polygon: null
};

$(document).ready(function () {
    $('#kmlFile').hide();
    $('#map').hide();
    displayKmlFromDB();
});

//calculate Area
function displayKmlFromDB() {
    var kmlString = '<s:property value="land.kmlString"/>';
    var landId = '<s:property value="land.id"/>';
    if (kmlString != null && kmlString.length != 0) {
        /*var kmlReferenceNumber = '<s:property value="land.referenceNumber"/>';*/
        var kmlReferenceNumber = '<s:property value="land.getGeoParcelCode()"/>';
        var middlePoint = '<s:property value="land.kmlMiddlePoint"/>';

        $('#kmlFile').show();
        $('#map').show();
        var melbourne = new google.maps.LatLng(-122.0822035425683, 37.42228990140251);
        var mapOptions = {
            zoom:      12,
            center:    melbourne,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            draggableCursor: "crosshair"
        };
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true});

        var kml = "<kml><Placemark><name>Land</name><Polygon><extrude>1</extrude><altitudeMode>relativeToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>" + kmlString + " </coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark><Placemark><name>" + kmlReferenceNumber + "</name><description>Geographical Center</description><Point><coordinates>" + middlePoint + "</coordinates><referenceNo>" + kmlReferenceNumber + "</referenceNo></Point></Placemark></kml>";
        // alert(kmlString);
        geoXml.parseKmlString(kml);
        //  var coordinate = new google.maps.LatLng(6.904339, 79.919087);
        // var isWithinPolygon = geoXml.containsLocation(coordinate,kml);
        //  alert(isWithinPolygon);

        google.maps.event.addListener(map, "click", function(evt) {
            // When the map is clicked, pass the LatLng obect to the measureAdd function
            measureAdd(evt.latLng);
        });
        var landArea = '<s:property value="land.kmlLandArea"/>';
        if (landArea == null || landArea == 0) {
            calculateAreaFromDB(landId);
        } else {
            changeHectareKml();
        }
        measureReset();
      // warning messages
       var land_not_attached = $("input#land_not_attached").val();
       var geoPoint_not_valid = $("input#geoPoint_not_valid").val();
       var geoPoint_not_in_land = $("input#geoPoint_not_in_land").val();

       //Json call to get land image details
        $.getJSON('${pageContext.request.contextPath}/common/GPSImageService', {id:landId,type:"GPSImage"}, function(   data) {
            var lat;
            var lon;
            var coordinate ;
            var isWithinPolygon = 0;
            var coordinates = new Array();
          //   alert(data.DocIdList.length);
            if(data.DocIdList.length == 0)  {
                $('#messageBox').html(land_not_attached);
            } else {
                var count=0;
                jQuery.each(data.GPSMap, function(key, val) {
                     var docId;
                    for(var k =0 ; k < data.DocIdList.length ; ++k){
                         if(key == data.DocIdList[k].documentName){
                             docId = data.DocIdList[k].id ;
                         }
                    }

                    var path = '${pageContext.request.contextPath}/eLand/downloadFile.do?documentId='+docId;
                    var content =   '<div id ="heading>'+
                            '<h1 id="firstHeading" class="firstHeading">'+key+'</h1>'+
                            '</div>'+
                            '<div id="bodyContent">'+
                            '<img  id="imageAbc" src="'+path+'" width="200"/>'+
                            '</div>';
                    //alert(key+" "+val+" "+count+" "+data.DocIdList[count]);
                    lat = val.latitude;
                    lon = val.longitude;
                    coordinate = new google.maps.LatLng(lat,lon);
                    coordinates[count] = coordinate;
                    isWithinPolygon = 0;
                    var iconBase = 'http://maps.google.com/mapfiles/kml/pal2/';
                    var title = key ;
                    var  marker = new google.maps.Marker({
                        position: coordinate,
                        title:title,
                        /* icon : new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5))*/
                        icon : iconBase + 'icon13.png'
                    });
                    var infowindow = new google.maps.InfoWindow({
                     content:content
                     });
                     google.maps.event.addListener(marker, 'click', function() {
                     infowindow.open(map,marker);
                     });

                    marker.setMap(map);
                    count++;
                });

                var middleCordArray= middlePoint.split(',');
                var middleCoordinate = new google.maps.LatLng(middleCordArray[1],middleCordArray[0]);
                var  message = "";
                for (var i=0; i<geoXml.docs[0].gpolygons.length; i++) {

                    jQuery.each(data.GPSMap, function(key, val) {
                        lat = val.latitude;
                        lon = val.longitude;
                        coordinate = new google.maps.LatLng(lat,lon);
                        var length = google.maps.geometry.spherical.computeDistanceBetween(middleCoordinate,coordinate);
                        if (google.maps.geometry.poly.containsLocation(coordinate,geoXml.docs[0].gpolygons[i])) {
                            isWithinPolygon = 1;
                        } else if(google.maps.geometry.poly.isLocationOnEdge(coordinate,geoXml.docs[0].gpolygons[i],3*10e-5)){ //about 0-20 meters form the boundry
                            isWithinPolygon = 1;
                        } else if(length < 20){        // when less than     20 m from center point
                            isWithinPolygon = 1;
                        }  else{
                            message= message + geoPoint_not_in_land + " ["+key+"\]. <br>";
                        }
                    } )
                }

                jQuery.each(data.NoGeoPointList, function(index,val) {
                    message= message + geoPoint_not_valid + " ["+val+"\]. <br>";
                });

                $('#messageBox').html(message);

            }
        });
    }
}

//calculate Area
function calculateAreaFromDB(landId) {
    var area;
    var type = "kmlString";
    $.getJSON('${pageContext.request.contextPath}/common/LandLookupService', {type:type,id:landId}, function(data) {
        if (data != null && data.latLanVal != null) {
            var AList = data.latLanVal;
            var points = new Array();
            var Alenth = AList.length;
            var j = 0;
            for (i = 0; i < Alenth; i++) {
                points[j++] = new google.maps.LatLng(AList[i + 1], AList[i]);
                i++;
                measureAdd(points[j - 1]);
            }
            area = google.maps.geometry.spherical.computeArea(points);
            $('#kmlArea').val(area);
            changeHectareKml();
        }
    });
    return area;
}

function measureAdd(latLng) {
    // Add a draggable marker to the map where the user clicked
    var marker = new google.maps.Marker({
        map: map,
        position: latLng,
        draggable: true,
        raiseOnDrag: false,
        title: "Drag me to change shape",
        icon: new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5))
    });

    // Add this LatLng to our line and polygon MVCArrays
    // Objects added to these MVCArrays automatically update the line and polygon shapes on the map
    measure.mvcLine.push(latLng);
    measure.mvcPolygon.push(latLng);

    // Push this marker to an MVCArray
    // This way later we can loop through the array and remove them when measuring is done
    measure.mvcMarkers.push(marker);

    // Get the index position of the LatLng we just pushed into the MVCArray
    // We'll need this later to update the MVCArray if the user moves the measure vertexes
    var latLngIndex = measure.mvcLine.getLength() - 1;

    // When the user mouses over the measure vertex markers, change shape and color to make it obvious they can be moved
    google.maps.event.addListener(marker, "mouseover", function() {
        marker.setIcon(new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(15, 15), new google.maps.Point(0, 0), new google.maps.Point(8, 8)));
    });

    // Change back to the default marker when the user mouses out
    google.maps.event.addListener(marker, "mouseout", function() {
        marker.setIcon(new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5)));
    });

    // When the measure vertex markers are dragged, update the geometry of the line and polygon by resetting the
    //     LatLng at this position
    google.maps.event.addListener(marker, "drag", function(evt) {
        measure.mvcLine.setAt(latLngIndex, evt.latLng);
        measure.mvcPolygon.setAt(latLngIndex, evt.latLng);
    });

    // When dragging has ended and there is more than one vertex, measure length, area.
    google.maps.event.addListener(marker, "dragend", function() {
        if (measure.mvcLine.getLength() > 1) {
            measureCalc();
        }
    });

    // If there is more than one vertex on the line
    if (measure.mvcLine.getLength() > 1) {

        // If the line hasn't been created yet
        if (!measure.line) {

            //Create the line (google.maps.Polyline)
            measure.line = new google.maps.Polyline({
                map: map,
                clickable: false,
                strokeColor: "#FF0000",
                strokeOpacity: 1,
                strokeWeight: 3,
                path:measure.mvcLine
            });

        }

        // If there is more than two vertexes for a polygon
        if (measure.mvcPolygon.getLength() > 2) {

            // If the polygon hasn't been created yet
            if (!measure.polygon) {

                // Create the polygon (google.maps.Polygon)
                measure.polygon = new google.maps.Polygon({
                    clickable: false,
                    map: map,
                    fillOpacity: 0.25,
                    strokeOpacity: 0,
                    paths: measure.mvcPolygon
                });
            }
        }
    }
    // If there's more than one vertex, measure length, area.
    if (measure.mvcLine.getLength() > 1) {
        measureCalc();
    }
}

function measureCalc() {

    // Use the Google Maps geometry library to measure the length of the line
    var length = google.maps.geometry.spherical.computeLength(measure.line.getPath());
    jQuery("#span-length").text(length.toFixed(1))

    // If we have a polygon (>2 vertexes in the mvcPolygon MVCArray)
    if (measure.mvcPolygon.getLength() > 2) {
        // Use the Google Maps geometry library to measure the area of the polygon
        var area = google.maps.geometry.spherical.computeArea(measure.polygon.getPath());
        jQuery("#span-area").text(area.toFixed(1));

        viewUserCreteArea(area);
    }

}

function measureReset() {

    // If we have a polygon or a line, remove them from the map and set null
    if (measure.polygon) {
        measure.polygon.setMap(null);
        measure.polygon = null;
    }
    if (measure.line) {
        measure.line.setMap(null);
        measure.line = null
    }

    // Empty the mvcLine and mvcPolygon MVCArrays
    measure.mvcLine.clear();
    measure.mvcPolygon.clear();

    // Loop through the markers MVCArray and remove each from the map, then empty it
    measure.mvcMarkers.forEach(function(elem, index) {
        elem.setMap(null);
    });
    measure.mvcMarkers.clear();

    jQuery("#span-length,#span-area").text(0);

    $("#useracreId").text(0);
    $("#userroodsId").text(0);
    $("#userperchesId").text(0);
    $("#userhectareId").text(0);

}

function viewUserCreteArea(userArea) {

    var he = 0,ac = 0,ro = 0,pe = 0,temp = 0;
    var cont = 2.47105381467;
    he = userArea / 10000;

    if (1 > he > 0) {
        he = parseFloat(he);
    }
    ac = Math.floor(he * cont);
    temp = (he * cont - ac) * 4;
    ro = Math.floor(temp);
    temp = (temp - ro) * 40;
    pe = temp.toFixed(4);
    $("#useracreId").text(ac);
    $("#userroodsId").text(ro);
    $("#userperchesId").text(pe);
    $("#userhectareId").text(he.toFixed(4));
}
</script>
<tr id="kmlFile">
    <td colspan="4">
        <table>
            <tr><p><s:label value="%{getText('length.label')}"/> : <span id="span-length">0</span> m <br>
                <s:label
                        value="%{getText('area_grey_area.label')}"/>: <span
                        id="span-area">0</span> m² - <a href="javascript:measureReset();"><s:label
                        value="%{getText('reset_measure.label')}"/></a></p></tr>

            <tr><s:label value="%{getText('hectare.label')}"/> &nbsp;&nbsp; <s:label id="userhectareId" cssStyle="width: 80px;"/>
                </br>
                <s:label value="%{getText('acre.label')}"/> &nbsp;&nbsp; <s:label id="useracreId" cssStyle="width: 80px;"/> &nbsp;&nbsp;&nbsp;&nbsp;
                <s:label value="%{getText('roods.label')}"/> &nbsp;&nbsp; <s:label id="userroodsId" cssStyle="width: 80px;"/> &nbsp;&nbsp;&nbsp;&nbsp;
                <s:label value="%{getText('perches.label')}"/> &nbsp;&nbsp; <s:label id="userperchesId" cssStyle="width: 80px;"/>
            </tr>
            <%--<table>

                <tr>
                    <td><s:label value="%{getText('hectare.label')}"/></td>
                    <td><s:label id="userhectareId" cssStyle="width: 80px;"
                            /></td>
                </tr>
                <tr>
                    <td><s:label value="%{getText('acre.label')}"/></td>
                    <td><s:label id="useracreId" cssStyle="width: 80px;"/></td>
                    <td><s:label value="%{getText('roods.label')}"/></td>
                    <td><s:label id="userroodsId" cssStyle="width: 80px;"/></td>
                    <td><s:label value="%{getText('perches.label')}"/></td>
                    <td><s:label id="userperchesId" cssStyle="width: 80px;"
                            /></td>
                </tr>

            </table>--%>
            <tr>
                <td>
                    <div id="map">
                        <%--<s:label value="Land Map"/>--%>
                        <div id='map_canvas' style='height:500px; width: 750px'></div>
                    </div>
                </td>
            </tr>
        </table>
    </td>
</tr>
<s:hidden id="land_not_attached" value="%{getText('land_not_attached.label')}"/>
<s:hidden id="geoPoint_not_valid" value="%{getText('geoPoint_not_valid.label')}"/>
<s:hidden id="geoPoint_not_in_land" value="%{getText('geoPoint_not_in_land.label')}"/>